﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Web.Security;

namespace BLL.Concrete.Validations
{
    public class LoginData : IDataErrorInfo
    {
        public const string MatchEmailPattern =
            @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
     + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
     + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
     + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
        public String UserName { get; set; }
        public String Password { get; set; }
        public Boolean RememberMe { get; set; }

        #region IDataErrorInfo Members
        public string Error { get; set; }

        public string this[string columnName]
        {
            get
            {
                if ((columnName == "UserName") && UserName == null)
                {
                    Error = "Nombre de usuario invalido";
                    return "*";
                }
                //else if ((columnName == "Email") && !Regex.IsMatch(UserName, MatchEmailPattern))
                //{
                //    // regex
                //    Error = MyResources.Error.InvalidEmail;
                //    return "*";
                //}
                else if ((columnName == "Password") && Password == null)
                {
                    Error = "Contraseña invalida";
                    return "*";
                }
                return null;
            }
        }

        #endregion
    }

    #region Membership
    public interface IMembershipService
    {
        int MinPasswordLength { get; }      
        bool ValidateUser(string userName, string password);
        MembershipCreateStatus CreateUser(string userName, string password, string email);
        bool ResetPassword(String UserName);
        bool ChangePassword(string userName, string oldPassword, string newPassword);
    }

    public class AccountMembershipService : IMembershipService
    {
        private readonly MembershipProvider _provider;

        public AccountMembershipService()
            : this(null)
        {
        }

        public AccountMembershipService(MembershipProvider provider)
        {
            _provider = provider ?? Membership.Provider;
        }

        public int MinPasswordLength
        {
            get
            {
                return _provider.MinRequiredPasswordLength;
            }
        }

        public bool ValidateUser(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");

            return _provider.ValidateUser(userName, password);
        }

        public MembershipCreateStatus CreateUser(string userName, string password, string email)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");

            MembershipCreateStatus status;
            _provider.CreateUser(userName, password, email, null, null, true, null, out status);
            return status;
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
            if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            try
            {
                MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
                return currentUser.ChangePassword(oldPassword, newPassword);
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }

        public bool ResetPassword(String UserName)
        {
            Boolean __ret = true;
            MembershipUser __user = Membership.GetUser(UserName);
            String __newPass = new Random().Next(999999).ToString();

            try
            {
              /*  // mandar el password al correo.                    
                MyHelpers.Email.Email __mail = new MyHelpers.Email.Email();
                List<String> __to = new List<string>();
                __to.Add(__user.Email);

                StringBuilder __sb = new StringBuilder();
                __sb.AppendLine(MyResources.Global.UserName + " " + __user.Email);
                __sb.AppendLine("<br />");
                __sb.AppendLine(MyResources.Global.Password + " " + __newPass);

                // send
                __mail.SendEmailMessage("recovery@lidotel.com.ve",
                    __to,
                    (System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Contains("en")) ? "Your new password" : "Su nueva contraseña",
                    __sb.ToString());*/
            }
            catch
            {
                __ret = false;
            }

            // reset del password
            try
            {

                String __aux = __user.ResetPassword();
                __user.ChangePassword(__aux, __newPass);
            }
            catch
            {
                __ret = false;
            }
            return __ret;
        }
    }

    public interface IFormsAuthenticationService
    {
        void SignIn(string userName, bool createPersistentCookie);
        void SignOut();
    }

    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
    #endregion
}
